package com.krmes.mes.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;

import com.krmes.mes.app.AppContext;
import com.krmes.mes.base.BaseApplication;

import java.io.File;
import java.text.NumberFormat;
import java.util.UUID;

@TargetApi(14)
public class TDevice
{
    public static boolean GTE_HC = false;
    public static boolean GTE_ICS = false;
    public static final int NETTYPE_CMNET = 3;
    public static final int NETTYPE_CMWAP = 2;
    public static final int NETTYPE_WIFI = 1;
    public static boolean PRE_HC;
    private static Boolean _hasBigScreen = null;
    private static Boolean _hasCamera = null;
    private static Boolean _isTablet = null;
    private static Integer _loadFactor = null;
    public static float displayDensity = 0.0F;

    static {
        _hasBigScreen = false;
        _hasCamera = false;
        _isTablet = false;
        _loadFactor = 0;
        displayDensity = 0;
        GTE_ICS = VERSION.SDK_INT >= 14 ? true : false;
        GTE_HC = VERSION.SDK_INT >= 11 ? true : false;
        PRE_HC = VERSION.SDK_INT >= 11 ? false : true;
    }

    public static void cancelFullScreen(Activity paramActivity)
    {
        LayoutParams localLayoutParams = paramActivity.getWindow().getAttributes();
        localLayoutParams.flags = (0xFFFFFBFF & localLayoutParams.flags);
        paramActivity.getWindow().setAttributes(localLayoutParams);
        paramActivity.getWindow().clearFlags(512);
    }

    public static float dpToPixel(float paramFloat)
    {
        return paramFloat * (getDisplayMetrics().densityDpi / 160.0F);
    }

    public static String getCurCountryLan()
    {
        return BaseApplication.context().getResources().getConfiguration().locale.getLanguage() + "-" + BaseApplication.context().getResources().getConfiguration().locale.getCountry();
    }

    public static int getDefaultLoadFactor()
    {
        if (_loadFactor == null)
        {
            Integer localInteger = Integer.valueOf(0xF & BaseApplication.context().getResources().getConfiguration().screenLayout);
            _loadFactor = localInteger;
            _loadFactor = Integer.valueOf(Math.max(localInteger.intValue(), 1));
        }
        return _loadFactor.intValue();
    }

    public static float getDensity()
    {
        if (displayDensity == 0.0D) {
            displayDensity = getDisplayMetrics().density;
        }
        return displayDensity;
    }

    public static String getDevicNO()
    {
        if (!TextUtils.isEmpty(getDeviceId())) {
            return getDeviceId();
        }
        return " ";
    }

    public static String getDevice()
    {
        return Build.MODEL;
    }

    public static String getDeviceId()
    {
        TelephonyManager tm = (TelephonyManager)AppContext.getInstance().context().getSystemService(Context.TELEPHONY_SERVICE);//"phone"
        if (tm != null) {
            try {
                return tm.getDeviceId();
            }catch (Exception ex){
                return null;
            }

        }
        return null;
    }

//    public static String getMac(){
//        WifiManager wifi = (WifiManager) AppContext.getInstance().context().getSystemService(Context.WIFI_SERVICE);
//        WifiInfo info = wifi.getConnectionInfo();
//        String wifiMac = info.getMacAddress();
//        if(wifiMac != null && wifiMac.length() >0){
//
//            return wifiMac;
//        }else{
//            return null;
//        }
//    }

    public static String getDeviceId(Application app)
    {
        TelephonyManager localTelephonyManager = (TelephonyManager)app.getSystemService(Context.TELEPHONY_SERVICE);//"phone"
        if (localTelephonyManager != null) {
            return localTelephonyManager.getDeviceId();
        }
        return null;
    }
    public static DisplayMetrics getDisplayMetrics()
    {
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        ((WindowManager)BaseApplication.context().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(localDisplayMetrics);
        return localDisplayMetrics;
    }

    public static String getIMEI()
    {
        return ((TelephonyManager)BaseApplication.context().getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    }

    public static Intent getInstallApkIntent(File paramFile)
    {
        Intent localIntent = new Intent();
        localIntent.setFlags(268435456);
        localIntent.setAction("android.intent.action.VIEW");
        localIntent.setDataAndType(Uri.fromFile(paramFile), "application/vnd.android.package-archive");
        return localIntent;
    }

    public static int getNetworkType()
    {
        int netType = 0x0;
        NetworkInfo networkInfo =  ((ConnectivityManager)AppContext.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if(networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if(nType == 0) {
            String extraInfo = networkInfo.getExtraInfo();
            if(!StringUtils.isEmpty(extraInfo)) {
                if(extraInfo.toLowerCase().equals("cmnet")) {
                    netType = 0x3;
                    return netType;
                }
                netType = 0x2;
                return netType;
            }
        }
        if(nType == 0x1) {
            return netType;
        }
        return netType;
    }

    public static String getOSVersion()
    {
        return VERSION.RELEASE;
    }

    public static PackageInfo getPackageInfo(String paramString)
    {
        try
        {
            PackageInfo localPackageInfo = BaseApplication.context().getPackageManager().getPackageInfo(paramString, 0);
            return localPackageInfo;
        }
        catch (NameNotFoundException localNameNotFoundException)
        {
            TLog.error(localNameNotFoundException.getMessage());
        }
        return null;
    }

    public static String getPhoneType()
    {
        return Build.MODEL;
    }

    public static int[] getRealScreenSize(Activity activity)
    {
        int[] size = new int[0x2];
        int screenWidth = 0x0, screenHeight = 0x0;
        WindowManager w = activity.getWindowManager();
        Display d = w.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        d.getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;
        if((VERSION.SDK_INT >= 0xe) && (VERSION.SDK_INT < 0x11)) {
            try {
                screenWidth =  ((Integer)Display.class.getMethod("getRawWidth", new Class[0]).invoke(d, new Object[0])).intValue();
                screenHeight = ((Integer)Display.class.getMethod("getRawHeight", new Class[0]).invoke(d, new Object[0])).intValue();
            } catch(Exception localException2) {
            }
        }
        if(VERSION.SDK_INT >= 0x11) {
            try {
                Point realSize = new Point();
                Display.class.getMethod("getRealSize", new Class[] { Point.class }).invoke(d, new Object[] { realSize });
                screenWidth = realSize.x;
                screenHeight = realSize.y;
            } catch(Exception localException3) {
            }
        }
        size[0x0] = screenWidth;
        size[0x1] = screenHeight;
        return size;
    }

    public static float getScreenHeight()
    {
        return getDisplayMetrics().heightPixels;
    }

    public static float getScreenWidth()
    {
        return getDisplayMetrics().widthPixels;
    }

    public static int getStatuBarHeight()
    {
        try
        {
            Class localClass = Class.forName("com.android.internal.R$dimen");
            Object localObject = localClass.newInstance();
            int i = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
            int j = BaseApplication.context().getResources().getDimensionPixelSize(i);
            return j;
        }
        catch (Exception localException)
        {
            localException.printStackTrace();
        }
        return 38;
    }

    public static int getStatusBarHeight()
    {
        try
        {
            Class localClass = Class.forName("com.android.internal.R$dimen");
            Object localObject = localClass.newInstance();
            int i = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
            int j = BaseApplication.context().getResources().getDimensionPixelSize(i);
            return j;
        }
        catch (Exception localException)
        {
            localException.printStackTrace();
        }
        return 0;
    }

    public static String getUdid()
    {
        String str = BaseApplication.getPreferences().getString("udid", "");
        if (str.length() == 0)
        {
            Editor localEditor = BaseApplication.getPreferences().edit();
            Object[] arrayOfObject = new Object[1];
            arrayOfObject[0] = UUID.randomUUID();
            str = String.format("%s", arrayOfObject);
            localEditor.putString("udid", str);
            localEditor.commit();
        }
        return str;
    }

    public static String getVendor()
    {
        return Build.BRAND;
    }

    public static int getVersionCode()
    {
        try
        {
            int i = BaseApplication.context().getPackageManager().getPackageInfo(BaseApplication.context().getPackageName(), 0).versionCode;
            return i;
        }
        catch (NameNotFoundException localNameNotFoundException) {}
        return 0;
    }

    public static int getVersionCode(String paramString)
    {
        try
        {
            int i = BaseApplication.context().getPackageManager().getPackageInfo(paramString, 0).versionCode;
            return i;
        }
        catch (NameNotFoundException localNameNotFoundException) {}
        return 0;
    }

    public static String getVersionName()
    {
        try
        {
            String str = BaseApplication.context().getPackageManager().getPackageInfo(BaseApplication.context().getPackageName(), 0).versionName;
            return str;
        }
        catch (NameNotFoundException localNameNotFoundException) {}
        return "";
    }

    public static boolean gotoGoogleMarket(Activity paramActivity, String paramString)
    {
        try
        {
            Intent localIntent = new Intent();
            localIntent.setPackage("com.android.vending");
            localIntent.setAction("android.intent.action.VIEW");
            localIntent.setData(Uri.parse("market://details?id=" + paramString));
            paramActivity.startActivity(localIntent);
            return true;
        }
        catch (Exception localException)
        {
            localException.printStackTrace();
        }
        return false;
    }

    public static boolean hasBigScreen()
    {
        _hasBigScreen = (BaseApplication.context().getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
        return _hasBigScreen.booleanValue();
//        boolean bool1 = true;
//        if (_hasBigScreen == null) {
//            if ((0xF & BaseApplication.context().getResources().getConfiguration().screenLayout) < 3) {
//                break label71;
//            }
//        }
//        label71:
//        for (boolean bool2 = bool1;; bool2 = false)
//        {
//            Boolean localBoolean = Boolean.valueOf(bool2);
//            _hasBigScreen = localBoolean;
//            if (!localBoolean.booleanValue())
//            {
//                if (getDensity() <= 1.5F) {
//                    bool1 = false;
//                }
//                _hasBigScreen = Boolean.valueOf(bool1);
//            }
//            return _hasBigScreen.booleanValue();
//        }
    }

    public static final boolean hasCamera()
    {
        if(_hasCamera == null) {
            PackageManager pckMgr = BaseApplication.context().getPackageManager();
            boolean flag = pckMgr.hasSystemFeature("android.hardware.camera.front");
            boolean flag1 = pckMgr.hasSystemFeature("android.hardware.camera");
            boolean flag2 ;
            if((flag) || (flag1)) {
                flag2 = true;
            } else {
                flag2 = false;
            }
            _hasCamera = Boolean.valueOf(flag2);
        }
        return _hasCamera.booleanValue();

    }

    public static boolean hasHardwareMenuKey(Context paramContext)
    {
        if (PRE_HC) {
            return true;
        }
        if (GTE_ICS) {
            return ViewConfiguration.get(paramContext).hasPermanentMenuKey();
        }
        return false;
    }

    public static boolean hasInternet()
    {
        return ((ConnectivityManager)BaseApplication.context().getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
    }

    public static boolean hasStatusBar(Activity paramActivity)
    {
        return (0x400 & paramActivity.getWindow().getAttributes().flags) != 1024;
    }

    public static void hideAnimatedView(View paramView)
    {
        if ((PRE_HC) && (paramView != null)) {
            paramView.setPadding(paramView.getWidth(), 0, 0, 0);
        }
    }

    public static void hideSoftKeyboard(View paramView)
    {
        if (paramView == null) {
            return;
        }
        ((InputMethodManager)BaseApplication.context().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(paramView.getWindowToken(), 0);
    }

    public static void installAPK(Context paramContext, File paramFile)
    {
        if ((paramFile == null) || (!paramFile.exists())) {
            return;
        }
        Intent localIntent = new Intent();
        localIntent.setFlags(268435456);
        localIntent.setAction("android.intent.action.VIEW");
        localIntent.setDataAndType(Uri.fromFile(paramFile), "application/vnd.android.package-archive");
        paramContext.startActivity(localIntent);
    }

    public static boolean isHaveMarket(Context paramContext)
    {
        Intent localIntent = new Intent();
        localIntent.setAction("android.intent.action.MAIN");
        localIntent.addCategory("android.intent.category.APP_MARKET");
        int i = paramContext.getPackageManager().queryIntentActivities(localIntent, 0).size();
        boolean bool = false;
        if (i > 0) {
            bool = true;
        }
        return bool;
    }

    public static boolean isLandscape()
    {
        return BaseApplication.context().getResources().getConfiguration().orientation == 2;
    }

    public static boolean isPackageExist(String paramString)
    {
        try
        {
            PackageInfo localPackageInfo = BaseApplication.context().getPackageManager().getPackageInfo(paramString, 0);
            boolean bool = false;
            if (localPackageInfo != null) {
                bool = true;
            }
            return bool;
        }
        catch (NameNotFoundException localNameNotFoundException)
        {
            TLog.error(localNameNotFoundException.getMessage());
        }
        return false;
    }

    public static boolean isPortrait()
    {
        boolean bool = true;
        if (BaseApplication.context().getResources().getConfiguration().orientation != 1) {
            bool = false;
        }
        return bool;
    }

    public static boolean isScreenOn()
    {
        return ((PowerManager)BaseApplication.context().getSystemService(Context.POWER_SERVICE)).isScreenOn();
    }

    public static boolean isSdcardReady()
    {
        return "mounted".equals(Environment.getExternalStorageState());
    }

    public static boolean isTablet()
    {
        _isTablet =(BaseApplication.context().getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
            return _isTablet.booleanValue();
    }

    public static boolean isWifiOpen()
    {
        boolean bool = false;
        NetworkInfo[] arrayOfNetworkInfo = ((ConnectivityManager)BaseApplication.context().getSystemService(Context.CONNECTIVITY_SERVICE)).getAllNetworkInfo();
        for (int i = 0;; i++)
        {
            if (i >= arrayOfNetworkInfo.length) {
                return bool;
            }
            if (arrayOfNetworkInfo[i].getState() == State.CONNECTED)
            {
                if (arrayOfNetworkInfo[i].getType() == 0) {
                    bool = false;
                }
                if (arrayOfNetworkInfo[i].getType() == 1) {
                    bool = true;
                }
            }
        }
    }

    public static boolean isZhCN()
    {
        return BaseApplication.context().getResources().getConfiguration().locale.getCountry().equalsIgnoreCase("CN");
    }

    public static void openApp(Context paramContext, String paramString)
    {
        Intent localIntent = BaseApplication.context().getPackageManager().getLaunchIntentForPackage(paramString);
        if (localIntent == null) {
            localIntent = new Intent(paramString);
        }
        for (;;)
        {
            paramContext.startActivity(localIntent);
            return;
            //TLog.log("Action:" + localIntent.getAction());
        }
    }

    public static boolean openAppActivity(Context paramContext, String paramString1, String paramString2)
    {
        Intent localIntent = new Intent("android.intent.action.MAIN");
        localIntent.addCategory("android.intent.category.LAUNCHER");
        localIntent.setComponent(new ComponentName(paramString1, paramString2));
        try
        {
            paramContext.startActivity(localIntent);
            return true;
        }
        catch (Exception localException) {}
        return false;
    }

    public static void openCamera(Context paramContext)
    {
        Intent localIntent = new Intent();
        localIntent.setAction("android.media.action.STILL_IMAGE_CAMERA");
        localIntent.setFlags(885260288);
        paramContext.startActivity(localIntent);
    }

    public static void openDail(Context paramContext)
    {
        Intent localIntent = new Intent("android.intent.action.DIAL");
        localIntent.setFlags(268435456);
        paramContext.startActivity(localIntent);
    }

    public static void openDial(Context paramContext, String paramString)
    {
        paramContext.startActivity(new Intent("android.intent.action.DIAL", Uri.parse("tel:" + paramString)));
    }

    public static void openSMS(Context paramContext, String paramString1, String paramString2)
    {
        Intent localIntent = new Intent("android.intent.action.SENDTO", Uri.parse("smsto:" + paramString2));
        localIntent.putExtra("sms_body", paramString1);
        paramContext.startActivity(localIntent);
    }

    public static void openSendMsg(Context paramContext)
    {
        Intent localIntent = new Intent("android.intent.action.SENDTO", Uri.parse("smsto:"));
        localIntent.setFlags(268435456);
        paramContext.startActivity(localIntent);
    }

    public static String percent(double paramDouble1, double paramDouble2)
    {
        double d = paramDouble1 / paramDouble2;
        NumberFormat localNumberFormat = NumberFormat.getPercentInstance();
        localNumberFormat.setMinimumFractionDigits(2);
        return localNumberFormat.format(d);
    }

    public static String percent2(double paramDouble1, double paramDouble2)
    {
        double d = paramDouble1 / paramDouble2;
        NumberFormat localNumberFormat = NumberFormat.getPercentInstance();
        localNumberFormat.setMinimumFractionDigits(0);
        return localNumberFormat.format(d);
    }

    public static float pixelsToDp(float paramFloat)
    {
        return paramFloat / (getDisplayMetrics().densityDpi / 160.0F);
    }

    public static void sendEmail(Context paramContext, String paramString1, String paramString2, String... paramVarArgs)
    {
        try
        {
            Intent localIntent = new Intent("android.intent.action.SEND");
            localIntent.setType("message/rfc822");
            localIntent.putExtra("android.intent.extra.EMAIL", paramVarArgs);
            localIntent.putExtra("android.intent.extra.SUBJECT", paramString1);
            localIntent.putExtra("android.intent.extra.TEXT", paramString2);
            paramContext.startActivity(localIntent);
            return;
        }
        catch (ActivityNotFoundException localActivityNotFoundException)
        {
            localActivityNotFoundException.printStackTrace();
        }
    }

    public static void setFullScreen(Activity paramActivity)
    {
        LayoutParams localLayoutParams = paramActivity.getWindow().getAttributes();
        localLayoutParams.flags = (0x400 | localLayoutParams.flags);
        paramActivity.getWindow().setAttributes(localLayoutParams);
        paramActivity.getWindow().addFlags(512);
    }

    public static void showAnimatedView(View paramView)
    {
        if ((PRE_HC) && (paramView != null)) {
            paramView.setPadding(0, 0, 0, 0);
        }
    }

    public static void showSoftKeyboard(Dialog paramDialog)
    {
        paramDialog.getWindow().setSoftInputMode(4);
    }

    public static void showSoftKeyboard(View paramView)
    {
        ((InputMethodManager)BaseApplication.context().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(paramView, 2);
    }

    public static void showSystemShareOption(Activity paramActivity, String paramString1, String paramString2)
    {
        Intent localIntent = new Intent("android.intent.action.SEND");
        localIntent.setType("text/plain");
        localIntent.putExtra("android.intent.extra.SUBJECT", "分享：" + paramString1);
        localIntent.putExtra("android.intent.extra.TEXT", paramString1 + " " + paramString2);
        paramActivity.startActivity(Intent.createChooser(localIntent, "选择分享"));
    }

    public static void toogleSoftKeyboard(View paramView)
    {
        ((InputMethodManager)BaseApplication.context().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, 2);
    }

    public static void uninstallApk(Context paramContext, String paramString)
    {
        if (isPackageExist(paramString)) {
            paramContext.startActivity(new Intent("android.intent.action.DELETE", Uri.parse("package:" + paramString)));
        }
    }

    public int getSDKVersion()
    {
        return VERSION.SDK_INT;
    }

    public String getVersion()
    {
        try
        {
            String str = BaseApplication.context().getPackageManager().getPackageInfo(BaseApplication.context().getPackageName(), 0).versionName;
            return str;
        }
        catch (NameNotFoundException localNameNotFoundException)
        {
            localNameNotFoundException.printStackTrace();
        }
        return "0.0.0";
    }
}
